<script setup lang="jsx">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  NCard, NInput, NButton, NSelect, NDatePicker, NCheckbox, NRadioGroup, 
  NRadio, NDivider, NPagination, NEmpty, NSpin
} from 'naive-ui'

const router = useRouter()
const route = useRoute()

// 搜索表单数据
const searchForm = ref({
  keyword: '',
  author: '',
  publication: '',
  startDate: null,
  endDate: null,
  domain: '',
  sortBy: 'relevance',
  language: [],
 文献类型: []
})

// 筛选选项
const domainOptions = [
  { label: '计算机科学', value: 'computer_science' },
  { label: '人工智能', value: 'ai' },
  { label: '软件工程', value: 'software_engineering' },
  { label: '数据科学', value: 'data_science' },
  { label: '机器学习', value: 'machine_learning' }
]

const languageOptions = [
  { label: '中文', value: 'chinese' },
  { label: '英文', value: 'english' },
  { label: '日文', value: 'japanese' },
  { label: '德文', value: 'german' }
]

const literatureTypeOptions = [
  { label: '期刊论文', value: 'journal' },
  { label: '会议论文', value: 'conference' },
  { label: '学位论文', value: 'thesis' },
  { label: '专利', value: 'patent' },
  { label: '技术报告', value: 'report' }
]

// 搜索结果
const searchResults = ref([])
const totalResults = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const showAdvancedSearch = ref(false)
const searchHistory = ref([])
const searchSuggestions = ref([])
const showSuggestions = ref(false)

// 计算属性 - 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toISOString().split('T')[0]
}

// 监听路由参数，初始化搜索
onMounted(() => {
  // 从路由参数中获取搜索词
  if (route.query.q) {
    searchForm.value.keyword = route.query.q
    handleSearch()
  }
  
  // 加载搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})

// 实时搜索建议
watch(() => searchForm.value.keyword, (newValue) => {
  if (newValue.trim().length > 1) {
    // 模拟搜索建议
    searchSuggestions.value = [
      `${newValue} 应用`,
      `${newValue} 研究进展`,
      `${newValue} 综述`,
      `${newValue} 案例分析`
    ]
    showSuggestions.value = true
  } else {
    showSuggestions.value = false
  }
})

// 处理搜索
const handleSearch = () => {
  if (!searchForm.value.keyword.trim()) {
    return
  }
  
  loading.value = true
  currentPage.value = 1
  
  // 保存到搜索历史
  if (!searchHistory.value.includes(searchForm.value.keyword)) {
    searchHistory.value.unshift(searchForm.value.keyword)
    if (searchHistory.value.length > 10) {
      searchHistory.value.pop()
    }
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
  
  // 模拟搜索请求
  setTimeout(() => {
    // 模拟搜索结果数据
    searchResults.value = Array.from({ length: pageSize.value }, (_, i) => ({
      id: (currentPage.value - 1) * pageSize.value + i + 1,
      title: `${searchForm.value.keyword}相关研究：基于深度学习的${i + 1}号文献`,
      authors: '作者团队' + (i + 1),
      publication: '计算机学报',
      publishDate: `202${i % 4}-${(i % 12) + 1}-${(i % 28) + 1}`,
      citations: Math.floor(Math.random() * 200) + 10,
      abstract: '这是一篇关于' + searchForm.value.keyword + '的研究论文，探讨了相关技术在实际应用中的效果和挑战...'
    }))
    
    totalResults.value = 200 // 模拟总结果数
    loading.value = false
    showSuggestions.value = false
  }, 800)
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  handleSearch()
}

// 重置搜索表单
const resetForm = () => {
  searchForm.value = {
    keyword: '',
    author: '',
    publication: '',
    startDate: null,
    endDate: null,
    domain: '',
    sortBy: 'relevance',
    language: [],
    literatureType: []
  }
  searchResults.value = []
  totalResults.value = 0
}

// 清除搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 从历史记录搜索
const searchFromHistory = (keyword) => {
  searchForm.value.keyword = keyword
  handleSearch()
}

// 跳转到文献详情
const goToDetail = (id) => {
  router.push(`/lingTach/detail?id=${id}`)
}

// 切换高级搜索
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}
</script>

<template>
  <div class="search-layout">
    <!-- 搜索区域 -->
    <div class="search-container">
      <NCard class="search-form-card">
        <!-- 基础搜索 -->
        <div class="basic-search">
          <NInput
            v-model:value="searchForm.keyword"
            placeholder="输入关键词、标题、作者等..."
            class="main-search-input"
            @keyup.enter="handleSearch"
          />
          <div class="search-buttons">
            <NButton type="primary" size="large" @click="handleSearch">
              搜索
            </NButton>
            <NButton size="large" @click="toggleAdvancedSearch">
              {{ showAdvancedSearch ? '收起' : '高级搜索' }}
            </NButton>
          </div>
        </div>
        
        <!-- 搜索建议下拉框 -->
        <div v-if="showSuggestions && searchSuggestions.length > 0" class="suggestions-dropdown">
          <div
            v-for="suggestion in searchSuggestions"
            :key="suggestion"
            class="suggestion-item"
            @click="() => { searchForm.keyword = suggestion; handleSearch() }"
          >
            {{ suggestion }}
          </div>
        </div>

        <!-- 高级搜索 -->
        <div v-if="showAdvancedSearch" class="advanced-search">
          <NDivider />
          <div class="advanced-form-grid">
            <div class="form-item">
              <label>作者</label>
              <NInput v-model:value="searchForm.author" placeholder="输入作者姓名" />
            </div>
            <div class="form-item">
              <label>出版物</label>
              <NInput v-model:value="searchForm.publication" placeholder="输入出版物名称" />
            </div>
            <div class="form-item">
              <label>领域</label>
              <NSelect
                v-model:value="searchForm.domain"
                :options="domainOptions"
                placeholder="选择研究领域"
                clearable
              />
            </div>
            <div class="form-item">
              <label>排序方式</label>
              <NRadioGroup v-model:value="searchForm.sortBy">
                <NRadio value="relevance">相关性</NRadio>
                <NRadio value="date">日期</NRadio>
                <NRadio value="citations">引用量</NRadio>
              </NRadioGroup>
            </div>
            <div class="form-item">
              <label>发表时间</label>
              <div class="date-range">
                <NDatePicker
                  v-model:value="searchForm.startDate"
                  type="date"
                  placeholder="开始日期"
                  format="yyyy-MM-dd"
                />
                <span class="date-separator">至</span>
                <NDatePicker
                  v-model:value="searchForm.endDate"
                  type="date"
                  placeholder="结束日期"
                  format="yyyy-MM-dd"
                />
              </div>
            </div>
            <div class="form-item">
              <label>语言</label>
              <NSelect
                v-model:value="searchForm.language"
                :options="languageOptions"
                placeholder="选择语言"
                multiple
                clearable
              />
            </div>
            <div class="form-item">
              <label>文献类型</label>
              <NSelect
                v-model:value="searchForm.literatureType"
                :options="literatureTypeOptions"
                placeholder="选择文献类型"
                multiple
                clearable
              />
            </div>
          </div>
          <div class="advanced-actions">
            <NButton type="default" @click="resetForm">
              重置
            </NButton>
          </div>
        </div>
      </NCard>

      <!-- 搜索历史 -->
      <div v-if="searchHistory.length > 0" class="search-history">
        <div class="history-header">
          <span class="history-title">搜索历史</span>
          <span class="clear-history" @click="clearHistory">清除</span>
        </div>
        <div class="history-tags">
          <span
            v-for="item in searchHistory"
            :key="item"
            class="history-tag"
            @click="searchFromHistory(item)"
          >
            {{ item }}
          </span>
        </div>
      </div>
    </div>

    <!-- 搜索结果区域 -->
    <div class="results-container">
      <!-- 结果统计 -->
      <div v-if="totalResults > 0" class="results-stats">
        找到 {{ totalResults }} 条结果，用时 0.{{ Math.floor(Math.random() * 9) }} 秒
      </div>

      <!-- 结果列表 -->
      <div class="results-list">
        <NSpin v-if="loading" :show="loading" />
        <div v-else-if="searchResults.length === 0" class="no-results">
          <NEmpty description="暂无搜索结果" />
        </div>
        <div v-else>
          <NCard
            v-for="result in searchResults"
            :key="result.id"
            class="result-card mb-10px"
            @click="goToDetail(result.id)"
          >
            <div class="result-title">{{ result.title }}</div>
            <div class="result-meta">
              <span class="authors">{{ result.authors }}</span>
              <span class="separator">|</span>
              <span class="publication">{{ result.publication }}</span>
              <span class="separator">|</span>
              <span class="date">{{ result.publishDate }}</span>
              <span class="separator">|</span>
              <span class="citations">{{ result.citations }} 引用</span>
            </div>
            <div class="result-abstract">{{ result.abstract }}</div>
            <div class="result-actions">
              <button class="action-btn">预览</button>
              <button class="action-btn">收藏</button>
              <button class="action-btn">下载</button>
            </div>
          </NCard>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalResults > 0" class="pagination-container">
        <NPagination
          v-model:page="currentPage"
          v-model:page-size="pageSize"
          :page-count="Math.ceil(totalResults / pageSize)"
          :page-sizes="[10, 20, 50]"
          show-size-picker
          show-quick-jumper
          show-total
          :total="totalResults"
          @update:page="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.search-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: var(--bg-primary);
  overflow-y: auto;
}

.search-container {
  width: clamp(300px, 60%, 1200px);
  margin: 0 auto 20px;
}

.search-form-card {
  background-color: #ffffff;
  border-radius: var(--border-radius-lg);
  padding: 20px;
  box-shadow: var(--shadow-sm);
  position: relative;
}

.basic-search {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.main-search-input {
  flex: 1;
  min-width: 0;
  --n-height: 40px !important;
  font-size: 16px;
  border-radius: var(--border-radius-md);
}

.search-buttons {
  display: flex;
  gap: 8px;
}

.suggestions-dropdown {
  position: absolute;
  top: calc(100% - 20px);
  left: 20px;
  right: 20px;
  background-color: #ffffff;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-md);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  &:hover {
    background-color: var(--bg-secondary);
  }
}

.advanced-search {
  margin-top: 20px;
}

.advanced-form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  margin: 16px 0;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-separator {
  color: var(--text-tertiary);
}

.advanced-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.search-history {
  background-color: #ffffff;
  border-radius: var(--border-radius-lg);
  padding: 16px 20px;
  margin-top: 16px;
  box-shadow: var(--shadow-sm);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

.clear-history {
  font-size: 12px;
  color: var(--text-tertiary);
  cursor: pointer;
  &:hover {
    color: var(--primary-color);
  }
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  padding: 4px 12px;
  background-color: var(--bg-secondary);
  color: var(--primary-color);
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  &:hover {
    background-color: var(--primary-color);
    color: #ffffff;
  }
}

.results-container {
  width: clamp(300px, 60%, 1200px);
  margin: 0 auto;
  flex: 1;
}

.results-stats {
  font-size: 14px;
  color: var(--text-tertiary);
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color);
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background-color: #ffffff;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

.result-card {
  background-color: #ffffff;
  border-radius: var(--border-radius-lg);
  padding: 20px;
  box-shadow: var(--shadow-sm);
  cursor: pointer;
  transition: all 0.3s ease;
  &:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
  }
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 8px;
  line-height: 1.4;
}

.result-meta {
  font-size: 13px;
  color: var(--text-secondary);
  margin-bottom: 12px;
  line-height: 1.6;
}

.separator {
  color: var(--text-tertiary);
  margin: 0 8px;
}

.result-abstract {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 4px 12px;
  border: 1px solid var(--border-color);
  background-color: #ffffff;
  color: var(--text-secondary);
  border-radius: var(--border-radius-md);
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  &:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px 0;
  background-color: #ffffff;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

@media (max-width: 768px) {
  .search-layout {
    padding: 12px;
  }
  .basic-search {
    flex-direction: column;
  }
  .search-buttons {
    width: 100%;
  }
  .advanced-form-grid {
    grid-template-columns: 1fr;
  }
  .result-meta {
    flex-direction: column;
    gap: 4px;
  }
  .separator {
    display: none;
  }
}
</style>